#include <QPainter>
#include <QGridLayout>
#include <QTime>
#include <QString>

#include "imagewidget.h"
#include "connectionwindow.h"
#include "addcontrol.h"

#include <QDebug>

ImageWidget::ImageWidget(QWidget *parent) : QWidget(parent)
{
    ip = "127.0.0.1";
    port = 10000;
    addr = "Unknown address";
    camnum = 1;

    frame = new QFrame(this);
    frame->setFixedSize(320,240);
    frame->setFrameShape(QFrame::Box);//边框
    frame->setStyleSheet("color:black");

    image.load(":/uncon.png");

    //To show the IP and PORT of connected server
    addrlbl = new QLabel("ADDR", this);
    addrlbl->setStyleSheet("color:yellow");
    addrlbl->setAlignment(Qt::AlignLeft);
    addrlbl->setFont(QFont("Monospace", 12, QFont::Bold));

    //to show some information of video such as device position
    statelbl = new QLabel("VideoInfo", this);
    statelbl->setStyleSheet("color:yellow");
    statelbl->setAlignment(Qt::AlignLeft);
    statelbl->setFont(QFont("Monospace", 12, QFont::Normal));

    //The buttons to control video
    //connect button
    connbtn = new QPushButton(this);
    connbtn->setIcon(QIcon(":/camera.png"));
    connbtn->setIconSize(QSize(32, 32));
    connbtn->setToolTip("Connect");//设置提示
    connbtn->setFlat(true);//background glassy
    connbtn->setFixedSize(32, 32);
    connbtn->setEnabled(true);
    //pause button
    pausebtn = new QPushButton(this);
    pausebtn->setIcon(QIcon(":/pause.png"));
    pausebtn->setIconSize(QSize(32, 32));
    pausebtn->setToolTip("Pause");
    pausebtn->setFlat(true);
    pausebtn->setFixedSize(32, 32);
    pausebtn->setEnabled(false);
    pauseflag = 1;
    //take photo button
    cambtn = new QPushButton(this);
    cambtn->setIcon(QIcon(":/shoot.png"));
    cambtn->setIconSize(QSize(32, 32));
    cambtn->setToolTip("take photos");
    cambtn->setFlat(true);
    cambtn->setFixedSize(32, 32);
    cambtn->setEnabled(false);
    //stop button
    stopbtn = new QPushButton(this);
    stopbtn->setIcon(QIcon(":/stop1.png"));
    stopbtn->setIconSize(QSize(32, 32));
    stopbtn->setToolTip("Stop");
    stopbtn->setFlat(true);
    stopbtn->setFixedSize(32, 32);
    stopbtn->setEnabled(false);
    stopflag = 0;

    //list buttons in one row
    conlayout = new QHBoxLayout;
    conlayout->addWidget(connbtn);
    conlayout->addWidget(pausebtn);
    conlayout->addWidget(cambtn);
    conlayout->addWidget(stopbtn);

    //Gridiron plan.
    QGridLayout* mainLayout = new QGridLayout;
    mainLayout->setContentsMargins(0, 0, 0, 0);
    mainLayout->setVerticalSpacing(0);
    mainLayout->addWidget(frame, 0, 0);
    mainLayout->addWidget(addrlbl, 1, 0, Qt::AlignLeft|Qt::AlignTop);
    mainLayout->addWidget(statelbl, 2, 0, Qt::AlignLeft|Qt::AlignTop);

    mainLayout->addLayout(conlayout, 1, 2, 2, 1, Qt::AlignRight);

    this->setLayout(mainLayout);

    capthread = new MyThread(this);

    connect(connbtn, SIGNAL(clicked()), this, SLOT(connbtnClicked()));
    connect(capthread, SIGNAL(errorState(QString)), this, SLOT(setErrorState(QString)));
    connect(capthread, SIGNAL(curImgChanged(QImage)), this, SLOT(setImg(QImage)));
}

void ImageWidget::connbtnClicked()
{
    ConnectionWindow connDialog(this,ip,port,addr);
    connDialog.exec();

    if(connDialog.result() == QDialog::Accepted){
        ip   = connDialog.getIP();
        port = connDialog.getPort();
        addr = connDialog.getAddr();
            addrlbl->setText(QString("%1").arg(addr));
            statelbl->setText("Playing...");
            //start capture thread
            capthread->setHostAddress(ip,port,addr);
            capthread->start();
            //disconnect from connbtnClicked()
            connbtn->setIcon(QIcon(":/jiankong.png"));
            connbtn->setEnabled(true);
            disconnect(connbtn, SIGNAL(clicked()), this, SLOT(connbtnClicked()));

            //connect buttons for controling
            stopbtn->setIcon(QIcon(":/stop.png"));
            stopbtn->setEnabled(true);
            pausebtn->setIcon(QIcon(":/pause.png"));
            pausebtn->setEnabled(true);
            cambtn->setEnabled(true);

            connect(cambtn, SIGNAL(clicked()), this, SLOT(cambtnClicked()));
            connect(pausebtn, SIGNAL(clicked()), this, SLOT(pausebtnClicked()));
            connect(stopbtn, SIGNAL(clicked()), this, SLOT(stopbtnClicked()));
    }else{
        statelbl->setText("Canceled.");
    }
}

void ImageWidget::pausebtnClicked()
{
    if(pauseflag){
        pausebtn->setIcon(QIcon(":/start1.png"));
        pauseflag = 0;
        statelbl->setText("Paused ...");
        statelbl->setStyleSheet("color:yellow");
        disconnect(capthread, SIGNAL(curImgChanged(QImage)), this, SLOT(setImg(QImage)));
    }else{
        pausebtn->setIcon(QIcon(":/pause.png"));
        pauseflag = 1;
        statelbl->setText("playing...");
        statelbl->setStyleSheet("color:green");
        connect(capthread, SIGNAL(curImgChanged(QImage)), this, SLOT(setImg(QImage)));
    }
}

void ImageWidget::stopbtnClicked()
{
    stopflag ++;
    //to show current state
    addrlbl->setText(QString("%1:%2").arg(ip).arg(port));
    statelbl->setText("Record stopped.");
    statelbl->setStyleSheet("color:green");

    capthread->stopCapture();
    capthread->wait();

    //reset the control buttons
    image.load(":/uncon.png");
    frame->update();
    connbtn->setIcon(QIcon(":/camera.png"));
    connect(connbtn, SIGNAL(clicked()), this, SLOT(connbtnClicked()));
    pausebtn->setIcon(QIcon(":/pause.png"));
    pausebtn->setEnabled(false);
    disconnect(pausebtn, SIGNAL(clicked()), this, SLOT(pausebtnClicked()));
    cambtn->setEnabled(false);
    disconnect(cambtn, SIGNAL(clicked()), this, SLOT(cambtnClicked()));
    if(stopflag >= 2){
        disconnect(stopbtn, SIGNAL(clicked()), this, SLOT(stopbtnClicked()));
        stopbtn->setEnabled(false);
        stopflag = 0;
    }
}

void ImageWidget::cambtnClicked()
{
    QString picname("./photos/%1_%2.jpeg");
    picname = picname.arg(this->addr).arg(camnum);

    char name[255];
    strcpy(name, picname.toUtf8().data());
    FILE* fp = fopen(name, "w");
    this->image.save(picname);
    camnum++;
    fclose(fp);
    //qDebug() << picname;
}

void ImageWidget::setErrorState(QString err)
{
    statelbl->setText(err);
}

void ImageWidget::setImg(QImage image)
{
    this->image = image;
    this->update();
}

void ImageWidget::paintEvent(QPaintEvent *)
{
    QPainter painter(this);

    QRect source(0, 0, image.width(), image.height());
    QRect target(0, 0, frame->width(), frame->height());
    painter.drawImage(target, image, source);
}
